<template>
  <div>
    <el-row>
      <el-col :span="6" :offset="9">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="ruleForm.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

  </div>
</template>

<script>
  export default {
    name: "AddShopType",
    data() {
      var repetition = (rule, value, callback) => {
        this.$axios.get("shopType/ckShopType.action/" + value)
          .then(res => {
            if (res.data.code > 1) {
              callback();
            } else {
              callback(new Error(res.data.msg));
            }
          })
          .catch(err => {
            this.$message.error(err)
          })
      };
      return {
        rules: {
          name: [
            {required: true, message: '请输入类别名称', trigger: 'blur'},
            {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'},
            {validator: repetition, trigger: 'blur'}
          ],
        },
        ruleForm: {
          name: '',
        },
      }
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$axios
              .post("shopType/shopType.action", this.ruleForm)
              .then(res => {
                if (res.data.code > 0) {
                  this.$message.success(res.data.msg);
                  this.resetForm("ruleForm");
                }
              })
              .catch(err => {
                this.$message.error(err)
              })
          } else {
            this.$message.error('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style scoped>

</style>
